<?php
/**
 * Description of Class_Connexion
 *
 * @author Fantastik78
 */

    class Member {

    //Inputs Fields
        private $pseudo = "pseudo";
        private $pwd = "password";
        private $pwd_verif = "password_verif";
        private $mail = "email";
        private $mail_verif = "email_verif";
        private $last_name = "last_name";
        private $first_name = "first_name";

    //Change on Input Field
        private $trim_pseudo;
        private $trim_pwd;
        private $trim_last_name;
        private $trim_first_name;
        private $hashed_pwd;

    // ERRORS
        // Subscription Function
        private $e_field_name = array();
        private $e_subscription = false;
        private $e_mail = false;
        private $e_trim_pseudo = false;
        private $e_bad_pseudo = false;
        private $e_trim_pwd = false;
        private $e_bad_password = false;
        private $e_same_mail = false;
        private $e_pseudo_already_exist = false;
        private $e_mail_already_exist = false;
        private $e_trim_last_name = false;
        private $e_trim_first_name = false;
        private $e_same_pwd = false;
        // Login Function
        private $e_empty_post = false;
        private $e_empty_ps_log = false;
        private $e_member_not_exist = false;
        // setInformations Function
        private $e_format_telephone = false;
        private $e_format_mail = false;
        //setNewPassword Function
        private $e_not_same_pwd = false;
        private $e_new_password = false;
        private $e_old_password = false;


    public function  __construct() {}


    // Hash the password
    private function hashMDP($mdp_send){
        $prefix = "EfGGiGHdRvUtBuGG";
        $suffix = "pNHhjBNghBfgVRvr";

        $mdp_send = sha1($prefix . $mdp_send . $suffix);
        return $mdp_send;
    }

    // Check the login format
    private function verifLogin($login){
        if(preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_\-]+[a-zA-Z0-9]$/', $login) == 1){
            return true;
        }else{
            return false;
        }
    }

    // Check the password format
    private function verifPassword($password){
        if(preg_match("/^[^\'\"][\w\d\s-_]+[^\'\"]$/", $password) == 1){
            return true;
        }else{
            return false;
        }
    }

    // Check the email format
    private function verifEmail($email){

            if(preg_match('/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/', $email) == 1){
                return true;
            }else{
                return false; ;
            }
    }

    private function verifPhone($phone){
        if(preg_match('/^0[1-6]{1}(([0-9]{2}){4})|((\s[0-9]{2}){4})|((-[0-9]{2}){4})$/', $phone)){
            return true;
        }else{
            return false;
        }
    }

    // Create a unique key for a member
    public static function getUniqueKey($lenght) {
        $active_key = "";
        $ABC = "abcdefghijklmnpqrstuvwxy0123456789";
        srand((double)microtime()*1000000);

        for($i=0; $i<$lenght; $i++) {
            $active_key .= $ABC[rand()%strlen($ABC)];
        }
        return $active_key;
    }

    // Send a email for the confirmation
    private function sendConfirmationEmail($UniqueKey, $login, $Email){

        $validation_URL = "http://localhost/account_validation?login=" . $login . "&key=" . $UniqueKey;

        $headers ='From: "GesTeam\'s System"<system@gesteam.fr>'."\n";
        $headers .='Reply-To:'. 'contact@gesteam.fr' . "\n";
        $headers .='Content-Type: text/plain; charset="iso-8859-1"'."\n";
        $headers .='Content-Transfer-Encoding: 8bit';
        $email_subject = "Enregistrement GesTeam Utilisateur " . $login;
        $email_body =   "Félicitations " . $login . ", la création de votre compte GesTeam est terminée.\n\n
                        Vous devez cependant valider votre comtpe. Pour cela veuillez suivre l'adresse ci dessous:\n" .
                        $validation_URL . "\n\nSi vous avez reçu ce message alors qu'il ne vous était pas destiné, ".
                        "aucune action supplémentaire de votre part n'est nécessaire et vous pouvez ignorer ce message.";

        mail($Email, $email_subject, $email_body, $headers);
    }

    // Get the subscription errors
    public function getErrorsSubscription(){
        if(isset($_POST) && $this->e_subscription){
            echo "Vous devez remplir tous les champs.";
        }elseif(!empty($_POST)){

            if($this->e_pseudo_already_exist){echo "Le pseudo que vous avez choisi est déjà utilisé.<br/>";}
            if($this->e_mail_already_exist){echo "L'email que vous avez choisi est déjà utilisé.<br/>";}
            if($this->e_same_pwd){echo "Les mots de passe ne sont pas les mêmes.<br/>";}
            if($this->e_same_mail){echo "Les emails ne sont pas les mêmes.<br/>";}
            if($this->e_mail){echo "Le format de l'email est incorrect.<br/>";}
            if($this->e_trim_pseudo){echo "Le pseudo n'est rempli que d'espace, il doit contenir des caractères alphanumeriques.<br/>";}
            if($this->e_bad_pseudo){echo "Le pseudo ne doit contenir que des caractères alphanumeric et les symboles suivants : &#45;, &#95; d'une longueur minimum de 2 caractères";}
            if($this->e_trim_pwd){echo "Le mot de passe n'est rempli que d'espace, il doit contenir des caractères alphanumeriques.<br/>";}
            if($this->e_bad_password){echo "Le mot de passe ne doit contenir que des caractères alphanumeric et les symboles suivants : &#45;, &#95; d'une longueur minimum de 6 caractères";}
            if($this->e_trim_last_name){echo "Le nom n'est rempli que d'espace, il doit contenir des caractères alphanumeriques.<br/>";}
            if($this->e_trim_first_name){echo "Le prenom n'est rempli que d'espace, il doit contenir des caractères alphanumeriques.<br/>";}
        }
    }

    // Allow a user to subscribe
    public function subscription(){

        //Check $_POST
        if(isset($_POST['valider_form'])){
            if(empty($_POST)){
                $this->e_subscription = true;
            }else{

                //Securing $_POST
                $post_secu = array_map("mysql_real_escape_string", $_POST);

                //Check Inputs Fields
                $needed_fields = array($this->pseudo, $this->pwd, $this->pwd_verif, $this->mail, $this->mail_verif, $this->last_name, $this->first_name);
                $error_post_field = false;
                $error_field_name = array();

                foreach ($needed_fields as $field){
                    if(empty($_POST[$field])){
                        $error_post_field = true;
                        array_push($this->e_field_name, $field);
                    }
                }

                if($error_post_field){
                    $this->e_subscription = true;
                // Check Error on pseudo
                }else{
                    $this->trim_pseudo = trim($post_secu[$this->pseudo]);

                    if($this->trim_pseudo != null){
                        // Check pseudo format
                        if($this->verifLogin($this->trim_pseudo)){
                            //Check pwd validity
                            $this->trim_pwd = trim($this->pwd);
                            if($this->trim_pwd != null && $this->trim_pwd != $post_secu[$this->pwd]){
                                // Check password format
                                if($this->verifPassword($this->trim_pwd)){
                                    //Check equality on password
                                    if($post_secu[$this->pwd] == $post_secu[$this->pwd_verif]){
                                        $this->hashed_pwd = $this->hashMDP($post_secu[$this->pwd]);
                                        //Check mail validity
                                        if($this->verifEmail($post_secu[$this->mail])){
                                            //Check equality on mails
                                            if($post_secu[$this->mail] != $post_secu[$this->mail_verif]){
                                                $this->e_same_mail = true;
                                            }
                                        }else{
                                            $this->e_mail = true;
                                        }
                                    }else{
                                        $this->e_same_pwd = true;
                                    }
                                }else{
                                    $this->e_bad_password = true;
                                }
                            }else{
                                $this->e_trim_pwd = true;
                            }
                        }else{
                            $this->e_bad_pseudo = true;
                        }
                    }else{
                        $this->e_trim_pseudo = true;
                    }

                    $this->trim_last_name = trim($post_secu[$this->last_name]);
                    $this->trim_first_name = trim($post_secu[$this->first_name]);


                    if($this->trim_last_name == null){
                        $this->e_trim_last_name = true;
                    }

                    if($this->trim_first_name == null){
                        $this->e_trim_first_name = true;
                    }

                    if(!$this->e_mail && !$this->e_trim_pseudo && !$this->e_bad_pseudo && !$this->e_trim_pwd && !$this->e_bad_password && !$this->e_same_mail && !$this->e_same_pwd &&!$this->e_trim_last_name && !$this->e_trim_first_name){
                        //Check Disponibility of pseudo and mail
                        $query_nber_pseudo = mysql_query("SELECT COUNT(*) as nber FROM member WHERE pseudo='" . $this->trim_pseudo . "'");
                        $query_nber_mail = mysql_query("SELECT COUNT(*) as nber FROM member WHERE mail='" . $post_secu[$this->mail] . "'");
                        $nber_pseudo = mysql_fetch_array($query_nber_pseudo);
                        $nber_mail = mysql_fetch_array($query_nber_mail);

                        if($nber_mail['nber'] >= 1){ $this->e_mail_already_exist = true;}
                        if($nber_pseudo['nber'] >= 1){ $this->e_pseudo_already_exist = true;}

                        if(!$this->e_pseudo_already_exist && !$this->e_mail_already_exist){
                            //Inserting data into the database
                            $this->active_key = $this->getUniqueKey(25);
                            if(!mysql_query("INSERT INTO member (pseudo, password, mail, first_name, last_name, valid_key) VALUES ('" . $this->trim_pseudo . "', '". $this->hashed_pwd . "', '". $post_secu[$this->mail] . "', '" . $post_secu[$this->last_name] . "', '" . $post_secu[$this->first_name]. "', '" . $this->active_key . "')")){echo "FAIL";}
                            //$this->sendConfirmationEmail($this->active_key, $this->trim_pseudo, $post_secu[$this->mail]);
                        }
                    }
                }
            }
        }
    }

    // Get login errors
    public function getErrorsLogin(){
        if(isset($_POST) && !$this->e_empty_post){
            if($this->e_empty_post || $this->e_empty_ps_log){ echo "le champs mot de passe et/ou le champs login n'a pas été rempli";}
            if($this->e_member_not_exist){echo "La combinaison login et mot de passe ne correspond à aucun membre";};
        }
    }

    // Allow a member to login in
    public function login(){
        if(isset($_POST['valider_form'])){
            if($_POST[$this->pseudo] != null && $_POST[$this->pwd] != null){
                $post_secu = array_map("mysql_real_escape_string", $_POST);
                $this->hashed_pwd = $this->hashMDP($post_secu[$this->pwd]);
                $query = mysql_query("SELECT COUNT(*) as member_exist, id_member FROM member WHERE pseudo='" . $post_secu[$this->pseudo] . "' AND password='" . $this->hashed_pwd . "' AND status='ON'");
                $resultat_query = mysql_fetch_array($query);
                if($resultat_query['member_exist'] == 1){
                    $_SESSION['member_session']['id'] = $resultat_query['id_member'];
                    header("Location: index.php");
                    exit;
                }else{
                    $this->e_member_not_exist = true;
                }
            }else{
                $this->e_empty_ps_log = true;
            }
        }else{
            $this->e_empty_post = true;
        }

    }

    public function getInformations(){
        if(isset($_SESSION['member_session']['id'])){
            $array_result = array();
            $query = mysql_query("SELECT * FROM member WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
            $res_query = mysql_fetch_array($query);
            $array_result = array('last_name'=>$res_query['last_name'], 'first_name'=>$res_query['first_name'], 'email'=>$res_query['mail'], 'phone'=>$res_query['phone'], 'address'=>$res_query['address']);

            foreach($array_result as $key=>$valeur){
                $array_result[$key] = htmlentities($valeur);
            }

            return $array_result;
        }
    }

    public function getErrorsSetInformations(){
        if(isset($_POST['btn_change_info'])){
            if($this->e_format_mail){ echo "Le format de l'email est incorrect.<br/>";}
            if($this->e_format_telephone){ echo "Le format du telephone est incorrect.<br/>";}
        }
    }

    public function setInformations(){
        if(isset($_POST['btn_change_info'])){
            $post_secu = array_map("mysql_real_escape_string", $_POST);
            $table_fields = array ('last_name', 'first_name', 'email', 'phone', 'address');
            $table_res = array();

            $query_tmp = mysql_query("SELECT * FROM member WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
            $res_tmp = mysql_fetch_array($query_tmp);

            foreach ($table_fields as $value) {
                if($post_secu[$value] != null && trim($post_secu[$value]) != null){
                    switch ($value) {
                        case 'email': if($this->verifEmail($post_secu[$value])){$table_res[$value] = $post_secu[$value];}
                                        else{  $table_res[$value] = $res_tmp['mail'];
                                               $this->e_format_mail = true;
                                            }
                            break;
                        case 'phone': if($this->verifPhone($post_secu[$value])){$table_res[$value] = $post_secu[$value];}
                                      else{ $table_res[$value] = null;
                                            $this->e_format_telephone = true;
                                          }
                            break;
                        default: $table_res[$value] = $post_secu[$value];
                            break;
                            
                    }
                }else{
                    switch($value){
                        case 'last_name' : $table_res[$value] = $res_tmp['last_name'];
                            break;
                        case 'first_name' : $table_res[$value] = $res_tmp['first_name'];
                            break;
                        case 'email' : $table_res[$value] = $res_tmp['mail'];
                            break;
                        default : $table_res[$value] = null;
                            break;
                    }
                }
            }
            
            $query_update = mysql_query("UPDATE member SET last_name='". $table_res['last_name'] . "', first_name='". $table_res['first_name'] . "', mail='". $table_res['email']
                . "', phone='". $table_res['phone'] . "', address='". $table_res['address'] . "' WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
        }
    }

    public function getErrorSetNewPassword(){
        if(isset($_POST['btn_change_info']) && !empty($_POST['old_password']) && !empty($_POST['password']) && !empty($_POST['password_verif'])){
            if($this->e_old_password){ echo "L'ancien mot de passe ne correspond pas.<br/>";}
            if($this->e_not_same_pwd){ echo "Le mot de passe et le mot de passe de vérification ne correspond pas.<br/>";}
            if($this->e_new_password){ echo "Le format du mot de passe ne correspond pas.<br/>";}
            
        }
    }

    public function setNewPassword(){
        if(isset($_POST['btn_change_info']) && !empty($_POST['old_password']) && !empty($_POST['password']) && !empty($_POST['password_verif'])){
            $post_secu = array_map("mysql_real_escape_string", $_POST);
            $query_tmp = mysql_query("SELECT * FROM member WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
            $res_tmp = mysql_fetch_array($query_tmp);

            if($res_tmp['password'] == $this->hashMDP($post_secu['old_password'])){
                if(trim($post_secu['password']) != null && $post_secu['password'] == $post_secu['password_verif']){
                    if($this->verifPassword($post_secu['password'])){
                        mysql_query("UPDATE member SET password='" . $this->hashMDP($_POST['password']) . "' WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
                    }else{
                        $this->e_new_password = true;
                    }
                }else{
                    $this->e_not_same_pwd = true;
                }
            }else{
                $this->e_old_password = true;
            }

        }
    }

    // Validate a member account
    public function validateMember(){
        if(!empty($_GET['pseudo']) && !empty($_GET['key'])){

            $get_secu = array_map("mysql_real_escape_string", $_GET);

            $query = mysql_query("SELECT COUNT(*) as exist FROM member WHERE pseudo='" . $get_secu['pseudo'] . "' AND valid_key='" . $get_secu['key'] . "'");
            $resultat_query = mysql_fetch_array($query);
            if($resultat_query['exist'] == 1){
                $query_update = mysql_query("UPDATE member SET status='ON' WHERE pseudo='" . $get_secu['pseudo'] . "'");
                echo "Votre compte a bien été activé.<br/> Vous allez être redirigé vers la page d'acceuil.";
                header('Refresh: 5;url=index.php');
                exit;
            }else{
                echo "Votre compte n'as pas peu être activé.<br/>Si vous avez cliqué sur le lien, réessayé en copiant le lien directement dans votre navigateur.";
                header('Refresh: 30;url=index.php');
                exit;
            }
        }else{
            echo "Nous ne sommes pas en mesure de valdier votre compte.<br/>Si vous avez cliqué sur le lien, réessayé en copiant le lien directement dans votre navigateur.";
        }
    }

    // Allow us to know if a member is connected
    public function isConnected(){
        if(!empty($_SESSION['member_session']['id'])){
            return true;
        }else{
            return false;
        }
    }

    // A appeler seulement si isConnected
    public function getPseudo(){

        $query_pseudo = mysql_query("SELECT pseudo FROM member WHERE id_member='" . $_SESSION['member_session']['id'] . "'");
        $res_pseudo = mysql_fetch_array($query_pseudo);

        return $res_pseudo['pseudo'];
    }

    // Disconnected a member
    public function deconnected(){
        if(isset($_GET['disconnect'])){
            session_destroy();
            header("Location: index.php");
            exit;
        }
    }
}
?>
